package top.forforever.srb.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import top.forforever.srb.common.util.JwtUtils;

import java.net.URI;
import java.util.List;

/**
 * @create: 2023/5/9
 * @Description:
 * @FileName: MyGlobalFilters
 * @自定义内容：
 */
@Component
public class MyGlobalFilters implements GlobalFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 鉴权过滤器 判断是否登录 token是否合法
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        RequestPath path = request.getPath();  //不带 http://...
        URI uri = request.getURI(); //完整路径 带 http://...

        List<String> tokens = request.getHeaders().get("token");
        if (tokens != null && tokens.size() > 0) {
            String token = tokens.get(0);
            if (!StringUtils.isEmpty(token)) {
                boolean checkToken = JwtUtils.checkToken(token);
                if (checkToken) {
                    Long userId = JwtUtils.getUserId(token);
                    request.mutate().header("userId",userId.toString());
                    exchange.mutate().request(request);
                }
            }
        }

        return chain.filter(exchange);
    }

}
